var allFilesUploaded = 0, allErrorFiles = 0, uploadStarted = false, totalNum = 0, totalSize = 0, filesFiled, files = "";
function fileQueued(file) {
	var This = this, fileProgress = new FileProgress(file, This.customSettings.progressTarget);
	totalNum += 1;
	totalSize += file.size;
	fileProgress.toggleCancel(true, This);
	if (!uploadStarted) {
		$(".upload-tips").addClass("hidden");
		$("#upload-btn").css( {
			opacity : 0,
			height : 0
		});
		$(".opt-btns, .upload-list, #upload-status").removeClass("hidden");
		$("#upload-status .num b").text(file.index + 1);
		$(".progressBarInProgress").addClass("hidden");
		if ($(".progressWrapper").length === 20) {
			$(".continue-wrapper").addClass("hidden")
		}
		updateTotal(totalNum, totalSize)
	}
}
function updateTotal(totalNum, totalSize) {
	$("#upload-status .num b").text(totalNum);
	$("#upload-status .total-size b").text(
			totalSize / 1024 < 1024 ? (totalSize / 1024).toFixed(1) + " KB" : (totalSize / 1024 / 1024)
					.toFixed(2)
					+ " MB")
}
function fileQueueError(file, code, msg) {
	var This = this;
	if (code === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
		alert("你选择了太多的文件,\n"
				+ (msg === 0 ? "达到了上传的上限" : "你最多可以选择 " + msg + " 个文件。"));
		return
	}
	var fileProgress = new FileProgress(file, this.customSettings.progressTarget);
	fileProgress.setError();
	fileProgress.toggleCancel(true, This);
	switch (code) {
	case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
		fileProgress.setStatus("文件过大");
		break;
	case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
		fileProgress.setStatus("不能上传大小为0的文件。");
		break;
	case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
		fileProgress.setStatus("文件格式有误");
		debug_message(this, "Invalid file type", file, d);
		break;
	default:
		if (file !== null) {
			fileProgress.setStatus("错误")
		}
		debug_message(this, code, file, msg);
		break
	}
}
function debug_message(obj, code, file, msg) {
	obj.debug("Error Code: " + code + ", File name: " + file.name + ", File size: "
			+ file.size + ", Message: " + msg)
}
function fileDialogComplete(selectedNum, queuedNum) {
	var This = this;
	if (selectedNum > 0) {
		document.getElementById(this.customSettings.cancelButtonId).disabled = false
	}
}
function uploadStart(file) {
	$(".continue-wrapper").addClass("hidden");
	$("#upload-start").val("上传中...").attr("disabled", "disabled");
	$(".progressBarInProgress").removeClass("hidden");
	var fileProgress = new FileProgress(file, this.customSettings.progressTarget);
	fileProgress.toggleCancel(true, this);
	return true
}
function uploadProgress(file, completeBytes, totalBytes) {
	var percent = Math.ceil((completeBytes / totalBytes) * 100);
	var fileProgress = new FileProgress(file, this.customSettings.progressTarget);
	fileProgress.setProgress(percent);
}
function uploadError(file, code, msg) {
	var This = this, fileProgress = new FileProgress(file, this.customSettings.progressTarget);
	fileProgress.setError();
	fileProgress.toggleCancel(true, This);
	allErrorFiles++;
	//console.log("uploadError" + allErrorFiles);
	fileProgress.setStatus("失败");
	fileProgress.removeDelIcon();
	$(".upload-list .delete").remove();
	switch (code) {
	case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
		fileProgress.setStatus("失败");
		debug_message(this, "HTTP Error", file, msg);
		break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
		fileProgress.setStatus("失败");
		debug_message(this, "Upload Failed", file, msg);
		break;
	case SWFUpload.UPLOAD_ERROR.IO_ERROR:
		fileProgress.setStatus("失败");
		debug_message(this, "IO Error", file, msg);
		break;
	case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
		fileProgress.setStatus("失败");
		debug_message(this, "Security Error", file, msg);
		break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
		debug_message(this, "Upload limit exceeded", file, msg);
		fileProgress.setStatus("失败");
		break;
	case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
		debug_message(this, "File validation failed", file, msg);
		fileProgress.setStatus("失败");
		break;
	case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
		if (this.getStats().files_queued === 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = true
		}
		fileProgress.setStatus("取消");
		fileProgress.setCancelled();
		updateTotal(totalNum -= 1, totalSize -= file.size);
		allErrorFiles--;
		if ($(".progressWrapper").length <= 20) {
			$(".continue-wrapper").removeClass("hidden")
		}
		break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
		fileProgress.setStatus("停止");
		break;
	default:
		fileProgress.setStatus("错误：" + code);
		debug_message(this, code, file, msg);
		break
	}
}
function uploadSuccess(file, data) {
	var fileProgress = new FileProgress(file, this.customSettings.progressTarget), json = $.parseJSON(data), This = this;
	if(!json || !json.success) {
		fileProgress.setError();
		if(json) {
			fileProgress.setStatus(json.errmsg);
		} else {
			fileProgress.setStatus("未知错误");
		}
		fileProgress.removeDelIcon(json.file);
		allErrorFiles++;
		//console.log("uploadSuccess" + allErrorFiles);
		fileProgress.toggleCancel(true, This, function() {
			fileProgress.disappear();
			decrease_upload_count(This);
		});
		return false;
	} else {
		fileProgress.setComplete();
		fileProgress.setStatus("成功");
		fileProgress.removeDelIcon(json.file);
		$(".upload-list .delete").remove();
		file.post.photo_file = json.file;
		filesFiled = $("#uploadFiles");
		files = filesFiled.val() + "|" + json.file;
		filesFiled.val(files)
	}

	fileProgress.toggleCancel(true, This, function() {
		$.post(This.customSettings.delUrl, "photo_file="+file.post.photo_file, function(json) {
			if(!json || !json.success) {
				fileProgress.setError();
				if(json) {
					fileProgress.setStatus("删除时：" + json.errmsg);
				} else {
					fileProgress.setStatus("删除时：未知错误");
				}
				allErrorFiles++;
				//console.log("toggleCancel" + allErrorFiles)
			} else {
				fileProgress.setCancelled();
				filesFiled = $("#uploadFiles");
				files = filesFiled.val().replace("|" + file.post.photo_file, "");
				filesFiled.val(files);
				setTimeout(function() {
					fileProgress.disappear()
				}, 2000);
				decrease_upload_count(This)
			}
		});
	});
}
function decrease_upload_count(uploader) {
	allFilesUploaded--;
	var status = uploader.getStats();
	status.successful_uploads--;
	uploader.setStats(status);
}
function uploadComplete(file) {
	if (this.getStats().files_queued === 0) {
//		$("#upload-start").val("上传完成")
		$("#" + this.customSettings.cancelButtonId)[0].disabled = true;
	} else {
//		this.startUpload();
	}
}
function queueComplete(allFiles) {
	$("#upload-start").val("开始上传").removeAttr("disabled");
	$(".opt-btns").addClass("hidden");
	allFilesUploaded += (allFiles - allErrorFiles);
	if (allFilesUploaded > 0) {
		//filesFiled.val(files.split("|")[1]);
		if (allFilesUploaded === allFiles) {
			$("#upload").submit();
			allErrorFiles = 0
		} else {
			$("#has-error").removeClass().find("b").text(allErrorFiles);
			$(".nextstep").removeClass("hidden")
		}
	} else {
		$(".continue-wrapper").removeClass("hidden");
		$("#has-error").removeClass().find("b").text(allErrorFiles);
		$(".nextstep").removeClass("hidden")
	}
	uploadStarted = false
};
function swfuploadLoadFailed() {
	$("#noflash").show();
	$("#old-portal").show()
}

function FileProgress(file, progressTarget) {
	this.progressTarget = progressTarget;
	var doc = document;
	this.fileProgressID = file.id;
	this.opacity = 100;
	this.height = 0;
	this.fileProgressWrapper = doc.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = doc.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;
		this.fileProgressElement = doc.createElement("div");
		this.fileProgressElement.className = "progressContainer";
		var delHref = doc.createElement("a");
		delHref.href = "#";
		delHref.className = "progressCancel";
		delHref.appendChild(doc.createTextNode("x"));
		var filenameSpan = doc.createElement("span");
		filenameSpan.className = "progressName";
		filenameSpan.appendChild(doc.createTextNode(file.name));
		var fileSizeSpan = doc.createElement("span");
		fileSizeSpan.className = "progressSize";
		fileSizeSpan.appendChild(doc.createTextNode(file.size / 1024 < 1024 ? (file.size / 1024)
				.toFixed(1)
				+ " KB" : (file.size / 1024 / 1024).toFixed(2) + " MB"));
		var barBackDiv = doc.createElement("div");
		barBackDiv.className = "progressBarBack";
		var barInDiv = doc.createElement("div");
		barInDiv.className = "progressBarInProgress";
		barBackDiv.appendChild(barInDiv);
		var barDiv = doc.createElement("div");
		barDiv.className = "progressBarStatus";
		barDiv.innerHTML = "&nbsp;";
		this.fileProgressElement.appendChild(delHref);
		this.fileProgressElement.appendChild(filenameSpan);
		this.fileProgressElement.appendChild(barDiv);
		this.fileProgressElement.appendChild(barBackDiv);
		this.fileProgressElement.appendChild(fileSizeSpan);
		this.fileProgressWrapper.appendChild(this.fileProgressElement);
		doc.getElementById(progressTarget).appendChild(this.fileProgressWrapper)
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild
	}
	this.height = this.fileProgressWrapper.offsetHeight
}
FileProgress.prototype.setProgress = function(percent) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].childNodes[0].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].childNodes[0].style.width = percent + "%"
};
FileProgress.prototype.setComplete = function() {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = ""
};
FileProgress.prototype.setError = function() {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = ""
};
FileProgress.prototype.setCancelled = function() {
	this.fileProgressElement.className = "progressContainer";
	if (this.fileProgressElement.childNodes[3]) {
		this.fileProgressElement.childNodes[3].className = "progressBarError";
		this.fileProgressElement.childNodes[3].style.width = ""
	}
	var This = this;
	setTimeout(function() {
		This.disappear()
	}, 200)
};
FileProgress.prototype.setStatus = function(statusText) {
	this.fileProgressElement.childNodes[2].innerHTML = statusText;
};
FileProgress.prototype.removeDelIcon = function() {
	$(this.fileProgressElement.childNodes[0]).remove()
};
FileProgress.prototype.toggleCancel = function(isShow, uploader, cancelFunc) {
	this.fileProgressElement.childNodes[0].style.visibility = isShow ? "visible"
			: "hidden";
	if (uploader) {
		if (cancelFunc) {
			this.fileProgressElement.childNodes[0].onclick = function() {
				cancelFunc()
			}
		} else {
			var fileId = this.fileProgressID;
			this.fileProgressElement.childNodes[0].onclick = function() {
				uploader.cancelUpload(fileId);
				return false
			}
		}
	}
};
FileProgress.prototype.disappear = function() {
	var opacity = 15, height = 4, timeout = 30;
	if (this.opacity > 0) {
		this.opacity -= opacity;
		if (this.opacity < 0) {
			this.opacity = 0
		}
		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters
						.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity
			} catch (e) {
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity="
						+ this.opacity + ")"
			}
		} else {
			this.fileProgressWrapper.style.opacity = this.opacity / 100
		}
	}
	if (this.height > 0) {
		this.height -= height;
		if (this.height < 0) {
			this.height = 0
		}
		this.fileProgressWrapper.style.height = this.height + "px"
	}
	if (this.height > 0 || this.opacity > 0) {
		var This = this;
		setTimeout(function() {
			This.disappear()
		}, timeout)
	} else {
		$(this.fileProgressWrapper).remove();
		if (!$("#"+this.progressTarget).children().length) {
			$(".upload-list, .opt-btns").addClass("hidden")
		}
	}
};